local ivs = LibStub("AceAddon-3.0"):NewAddon("VendorSearch", "AceConsole-3.0", "AceEvent-3.0")

local db
local money = GetMoney();
local totalitems = GetMerchantNumItems();
local Keyword
local KeyQuality
local KeyType
local KeySubType
local newItemId;
local idebug = false--for debug

ivs.ItemCategory = {GetAuctionItemClasses()};
ivs.ItemSubCategory = {}
do
	for i, type in ipairs(ivs.ItemCategory) do
		ivs.ItemSubCategory[type] = {GetAuctionItemSubClasses(i)}
	end
end

function ivs:OnInitialize()

end

function ivs:OnEnable()
	self:RegisterEvent("MERCHANT_SHOW")
end

function ivs:OnDisable()

end

---------------------
-- ivs side panel
---------------------
do
	local panel = CreateFrame("Frame", "IVendorSearchPanel", MerchantFrame);
	panel:SetWidth(187);
	panel:SetHeight(389);
	panel:ClearAllPoints()
	panel:SetPoint("TOPLEFT", MerchantFrame, "TOPRIGHT", -38, -8)

	local Top = panel:CreateTexture( nil, "BACKGROUND" );
	Top:SetTexture( "Interface\\AuctionFrame\\AuctionHouseDressUpFrame-Top" );
	Top:SetWidth(256);
	Top:SetHeight(256);
	Top:SetPoint("TOPLEFT");

	local Bottom = panel:CreateTexture( nil, "BACKGROUND" );
	Bottom:SetTexture( "Interface\\AuctionFrame\\AuctionHouseDressUpFrame-Bottom" );
	Bottom:SetWidth(256);
	Bottom:SetHeight(256);
	Bottom:SetPoint("TOPLEFT", Top, "BOTTOMLEFT", 0, 60);

	local panelframe = CreateFrame("Frame", nil, panel);
	panel.panelframe = panelframe;
	panelframe:SetPoint("TOPLEFT", 8, -16)
	panelframe:SetPoint("BOTTOMRIGHT", 8, -16);

	local label = panelframe:CreateFontString(nil, "ARTWORK", "GameFontNormal");
	label:SetPoint("TOPLEFT", -4, 6)
	label:SetText("iVendorSearch");

	local closebutton = CreateFrame("Button", nil, panelframe, "UIPanelCloseButton")
	closebutton:SetPoint("CENTER", panel, "TOPRIGHT", -16, -16);
	closebutton:SetScript("OnClick", function(self)
		self:GetParent():GetParent():Hide();
	end)

	local bg = closebutton:CreateTexture(nil, "BACKGROUND")
	bg:SetWidth(32)
	bg:SetHeight(32)
	bg:SetTexture([[Interface\AuctionFrame\AuctionHouseDressUpFrame-Corner]]);
	bg:SetPoint("TOPRIGHT", panel, -5, -5)

		--searchbox
	local searchbox = CreateFrame("EditBox", "MerchantFrameSearchFrame",panel,"InputBoxTemplate");
	ivs.searchbox = searchbox
	searchbox:SetAutoFocus(nil);
	searchbox:SetWidth(110)
	searchbox:SetHeight(29)
	searchbox:SetPoint("TOPLEFT", 10, -35);
	searchbox:SetText("");
	searchbox:SetScript("OnEnterPressed", function(self)
		Keyword = self:GetText();
		searchbox:ClearFocus()
		ivs:Search(Keyword)
	end)
	searchbox:SetScript("OnTextChanged", function(self)
		Keyword = self:GetText();
		ivs:Search(Keyword)
	end)
	--editbox title
	local searchtitle = searchbox:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	searchtitle:SetPoint("BOTTOMLEFT", searchbox, "TOPLEFT", 3, -2);
	searchtitle:SetText("名称");


	--refresh button
	local refreshbutton = CreateFrame("Button", "MerchantFrameRefreshButton", panel)
	refreshbutton:SetNormalTexture("Interface\\Buttons\\UI-RotationLeft-Button-Up");
	refreshbutton:SetPushedTexture("Interface\\Buttons\\UI-RotationLeft-Button-Down");
	refreshbutton:SetHighlightTexture("Interface\\Buttons\\UI-RotationLeft-Button-Up")
	refreshbutton:SetWidth(29)
	refreshbutton:SetHeight(29)
	refreshbutton:SetPoint("LEFT", searchbox, "RIGHT", -2, 0);
	refreshbutton:RegisterForClicks("AnyUp")

	--reset button
	local reset = CreateFrame("Button", "MerchantFrameResetButton", panel);
	reset:SetNormalTexture("Interface\\Buttons\\CancelButton-Up");
	reset:SetPushedTexture([[Interface\Buttons\CancelButton-Down]]);
	reset:SetHighlightTexture("Interface\\Buttons\\CancelButton-Highlight", "ADD");
	reset:SetWidth(39)
	reset:SetHeight(39)
	reset:SetPoint("LEFT", refreshbutton, "RIGHT", -8, -2);
	reset:RegisterForClicks("AnyUp")
	reset:SetScript("OnClick", function(self)
		ivs:ClearSearch()
	end)

	--物品品质
	local qualityMenu = CreateFrame("Frame", "MerchantFrameQualitySelectFrame", panelframe, "UIDropDownMenuTemplate")
	qualityMenu:SetHeight(26)
	qualityMenu:SetPoint("TOP", searchbox, "BOTTOM", -50, -20);
	qualityMenu:SetPoint("LEFT", -16, 0);
	qualityMenu:SetPoint("RIGHT", -25, 0);
	local function qualityMenuSelect(self)
		if self.arg1 ~= KeyQuality then
			UIDropDownMenu_SetSelectedValue(qualityMenu, self.value);
			KeyQuality = self.arg1;
			ivs:Search()
		end
	end
	local function qualityMenuInit(level)
		local info = UIDropDownMenu_CreateInfo();

		info = {
			text = "|cffcccccc(所有)"..FONT_COLOR_CODE_CLOSE,
			value = -1,
			arg1 = false,
			func = qualityMenuSelect
		};
		UIDropDownMenu_AddButton(info)

		for i = 0, #ITEM_QUALITY_COLORS do
			info = {
				text = ITEM_QUALITY_COLORS[i].hex.._G["ITEM_QUALITY"..i.."_DESC"]..FONT_COLOR_CODE_CLOSE,
				value = i,
				arg1 = i,
				func = qualityMenuSelect,
				checked = nil,
			}
			UIDropDownMenu_AddButton(info)
		end
	end
	_G[qualityMenu:GetName().."Middle"]:SetPoint( "RIGHT", -16, 0 );
	qualityMenu:EnableMouse(true);
	UIDropDownMenu_JustifyText(qualityMenu, "LEFT");
	UIDropDownMenu_Initialize(qualityMenu, qualityMenuInit);
	UIDropDownMenu_SetSelectedValue(qualityMenu, -1);

	--
	local label = qualityMenu:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	label:SetText("物品品质: ")
	label:SetPoint("BOTTOMLEFT", qualityMenu, "TOPLEFT", 24, 0)

	--物品价格
		--price>
	--[[local price1 = CreateFrame("EditBox", "MerchantFramePrice1EditFrame", panelframe, "InputBoxTemplate")
	price1:SetWidth(60);
	price1:SetHeight(29);
	price1:SetPoint("TOPLEFT", qualityMenu, "BOTTOMLEFT", 25, -18);
	price1:SetAutoFocus(nil);
	local label = price1:CreateFontString( nil, "OVERLAY", "GameFontHighlightSmall" );
	label:SetPoint( "LEFT", price1, "RIGHT" );
	label:SetText( "-" );
		--price<
	local price2 = CreateFrame("EditBox", "MerchantFramePrice2EditFrame", panelframe, "InputBoxTemplate")
	price2:SetWidth(60);
	price2:SetHeight(29);
	price2:SetPoint("LEFT", price1, "RIGHT", 10, 0);
	price2:SetAutoFocus(nil);
		--price title
	local labeltitle = price1:CreateFontString("MerchantFramePrice1EditTitle", "OVERLAY", "GameFontHighlightSmall");
	labeltitle:SetText("价格: ");
	labeltitle:SetPoint("BOTTOMLEFT", price1, "TOPLEFT", 0, 0);]]

	--type frame
	local typeframe = CreateFrame("Frame", "MerchantFrameCategoryTypeFrame", panelframe, "OptionsBoxTemplate");
	typeframe:SetPoint("TOPLEFT", qualityMenu, "BOTTOMLEFT", 17, -18);
	typeframe:SetWidth(160);
	typeframe:SetHeight(130);
	_G[typeframe:GetName().."Title"]:SetText("物品类别:");

	--category
	local typemenu = CreateFrame("Frame", "MerchantFrameCategorySection", panelframe, "UIDropDownMenuTemplate")
	typemenu:SetPoint("TOP", typeframe, 0, -20);
	typemenu:SetPoint("LEFT", typeframe, -8, 0);
	typemenu:SetPoint("RIGHT", typeframe, -8, 0);
	local function typemenuOnSection(self)
		if self.arg1 ~= KeyType then
			UIDropDownMenu_SetSelectedValue(typemenu, self.value);
			KeyType = self.arg1;
			UIDropDownMenu_SetSelectedValue(ivs.subtypemenu, -1);
			KeySubType = false
			ivs:Search();

			if not KeyType then
				UIDropDownMenu_DisableDropDown(ivs.subtypemenu)
			else
				UIDropDownMenu_EnableDropDown(ivs.subtypemenu)
			end
		end
	end
	local function typemenuInit()
		local info = UIDropDownMenu_CreateInfo();

		info = {
			text = "|cffcccccc(所有)"..FONT_COLOR_CODE_CLOSE,
			value = -1,
			arg1 = false,
			func = typemenuOnSection
		};
		UIDropDownMenu_AddButton(info)

		for index, itype in ipairs(ivs.ItemCategory) do
			info = {
				text = itype,
				value = index,
				arg1 = itype,
				func = typemenuOnSection,
				checked = nil
			}
			UIDropDownMenu_AddButton(info)
		end
	end
	_G[typemenu:GetName().."Middle"]:SetPoint( "RIGHT", -16, 0 );
	typemenu:EnableMouse(true);
	UIDropDownMenu_JustifyText(typemenu, "LEFT");
	UIDropDownMenu_Initialize(typemenu, typemenuInit);
	UIDropDownMenu_SetSelectedValue(typemenu, -1);

	local label = typemenu:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	label:SetText("类别: ")
	label:SetPoint("BOTTOMLEFT", typemenu, "TOPLEFT", 24, 0)
	--sub category
	local subtypemenu = CreateFrame("Frame", "MerchantFrameSubCategorySection", panelframe, "UIDropDownMenuTemplate");
	subtypemenu:SetPoint( "TOP", typemenu, "BOTTOM", 0, -10 );
	subtypemenu:SetPoint( "LEFT", typeframe, -8, 0 );
	subtypemenu:SetPoint( "RIGHT", typeframe, -8, 0 );
	ivs.subtypemenu = subtypemenu
	--ivs.ItemSubCategory
	local function subtypemenuOnSection(self)
		if self.arg1 ~= KeySubType then
			UIDropDownMenu_SetSelectedValue(subtypemenu, self.value);
			KeySubType = self.arg1;
			ivs:Search();
		end
	end
	local function subtypemenuInit()
		local info = UIDropDownMenu_CreateInfo();

		info = {
			text = "|cffcccccc(所有)"..FONT_COLOR_CODE_CLOSE,
			value = -1,
			arg1 = false,
			func = subtypemenuOnSection
		};
		UIDropDownMenu_AddButton(info)
		if KeyType then
			for index, itype in ipairs(ivs.ItemSubCategory[KeyType]) do
				info = {
					text = itype,
					value = index,
					arg1 = itype,
					func = subtypemenuOnSection,
					checked = nil
				}
				UIDropDownMenu_AddButton(info)
			end
		end
	end
	_G[subtypemenu:GetName().."Middle"]:SetPoint( "RIGHT", -16, 0 );
	subtypemenu:EnableMouse(true);
	UIDropDownMenu_JustifyText(subtypemenu, "LEFT");
	UIDropDownMenu_Initialize(subtypemenu, subtypemenuInit);
	UIDropDownMenu_SetSelectedValue(subtypemenu, -1);
	--disable
	UIDropDownMenu_DisableDropDown(subtypemenu);
	local label = typemenu:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	label:SetText("子类别: ")
	label:SetPoint("BOTTOMLEFT", subtypemenu, "TOPLEFT", 24, 0)
end

function ivs:ClearSearch()
	self.searchbox:SetText("输入关键词");
end

function ivs:MERCHANT_SHOW()
	self:MERCHANT_LIST();
	for i = 1, totalitems do
		local name, icon, price, quantity, numAvailable, isUsable, ext = GetMerchantItemInfo(i)
		local itemlink = GetMerchantItemLink(i)
		self.itemname = name
		self.Items = getglobal("MerchantItem"..i);

		if idebug and itemlink then
			print("Item "..i.." : "..itemlink.." - "..price.." copper");
		end
	end
	if Keyword and not(Keyword == "输入关键词") then
		self:Search(Keyword)
	end
end

function ivs:MERCHANT_LIST()
	totalitems = GetMerchantNumItems();
	if idebug then
		print("总共有: "..totalitems);
	end
end

function ivs:Search(keyword)
	UIErrorsFrame:UnregisterEvent("UI_ERROR_MESSAGE");
	self.found = 0
	local links = ""
	local CurrPage = MerchantFrame.page
	if idebug then
		print("当前为第..="..CurrPage.."页");
	end
	local searchstart = ((10 * CurrPage) - 10 + 1);
	local i = 1
	local itempage

	while GetMerchantItemInfo(i) and i <= searchstart+9 do
		CurrPage = MerchantFrame.page
		local name, icon, price, quantity, numAvailable, isUsable, extendedCost = GetMerchantItemInfo(i);
		local link = GetMerchantItemLink(i);
		self.itemname = name
		self.itemprice = price
		local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(link);
		local ipart = math.floor(i/10)
		if (i/10) == ipart then
			itempage = ipart
			newItemId = i - (10*ipart) + 1
			if i == 10 then
				newItemId = 10
			end
		else
			itempage = 1 + ipart
			newItemId = i - (10*ipart)
		end
		self.Items = getglobal("MerchantItem"..newItemId);
		if (Keyword and (not(Keyword == "输入关键词")) and string.find(string.lower(self.itemname), string.lower(Keyword))) or (KeyQuality and ((iRarity == KeyQuality) or (KeyQuality == false))) or (KeyType and (KeyType == sType)) or(KeySubType and (KeySubType == sSubType)) then
			if idebug then
				print(self.itemname.." is found");
			end

			self:montrer()
			self:Filter()
			self.found = self.found + 1
			if links == "" then
 				links = links .. link .. " - " .. price .. "c"
 			else
 				links = links .. " , \n" .. link .. " - " .. price .. "c"
 			end
		else
			self:cacher()
		end

		i=(i + 1)
	end
end

function ivs:cacher()
	self.Items:SetAlpha(0.15)
end

function ivs:montrer()
	self.Items:Show()
	self.Items:SetAlpha(1)
end

function ivs:Filter()

end